import React, { Component } from 'react'
import { Table, Button, Modal, Input, Popconfirm, Icon, Row, Col, Checkbox } from 'antd'
import * as fetch from '../../utils/http'


class RolePage extends Component {
    state = {
        modalTitle: '',
        roleName: '',
        id: '',
        roleID: '',
        menuList: [],
        selectedRowKeys: [],
        visible: false,
        visibleMenuModal: false
    }
    constructor(props) {
        super(props)
        this.getUser()
        fetch.get('GasMenu/GetMenus').then(res => {
            if (res.isSuccess) {
                const list = res.data
                const arr = []
                if (list.length) {
                    list.forEach((item, index) => {
                        arr.push(item)
                        if (item.children.length) {
                            arr.push(...item.children)
                        }
                    })
                }
                const lastArr = []
                arr.forEach((item, index) => {
                    const { id, menuName } = item
                    const obj = {
                        menuId: id,
                        menuName,
                        canAdd: false,
                        canUpdate: false,
                        canDelete: false,
                        canExport: false
                    }
                    lastArr.push(obj)
                })
                this.setState({ menuList: lastArr })
            }
        })
    }

    resetCan(arr) {
        const { menuList } = this.state
        menuList.forEach((item, index) => {
            item.canAdd = false;
            item.canUpdate = false;
            item.canDelete = false;
            item.canExport = false;
        })
        this.setState({
            menuList
        })
    }

    handleOk() {
        const { id } = this.state
        this.setState({
            visible: false
        })
        const params = {
            roleName: this.state.roleName
        }
        if (id) {
            params.id = id
            fetch.post('GasRole/Edit', params).then(res => {
                if (res.isSuccess) {
                    this.getUser()
                }
            })
        } else {
            fetch.post('GasRole/Add', params).then(res => {
                if (res.isSuccess) {
                    this.getUser()
                }
            })
        }
        this.setState({
            roleName: '',
            id: ''
        })
    }

    getUser() {
        fetch.get('GasRole/GetRoles').then(res => {
            if (res.isSuccess) {
                this.setState({
                    roleList: res.data
                })
            }
        })
    }

    handleCancel() {
        this.setState({
            visible: false,
            roleName: '',
            id: ''
        })
    }

    openModal() {
        this.setState({
            modalTitle: '新建角色',
            visible: true
        })
    }

    onRoleNameInput(e) {
        this.setState({
            roleName: e.target.value
        })
    }

    onDelUser(e) {
        this.setState({
            visible: false
        })
        fetch.post('GasRole/Delete', { id: e.id }).then(res => {
            this.getUser()
        })
    }

    openMenuModal(item) {
        if (item.roleMenus.length) {
            const selectedRowKeys = []
            const { menuList } = this.state;
            for (let child of item.roleMenus) {
                selectedRowKeys.push(child.menuID)
                let eachItem = menuList.filter(item => item.menuId === child.menuID)[0]
                eachItem.canAdd = child.canAdd
                eachItem.canDelete = child.canDelete
                eachItem.canExport = child.canExport
                eachItem.canUpdate = child.canUpdate
            }
            console.log('save', menuList)
            this.setState({
                selectedRowKeys,
                roleID: item.id,
                menuList,
                visibleMenuModal: true,
                // menuList: item.roleMenus
            })
        } else {
            this.setState({
                roleID: item.id,
                visibleMenuModal: true
            })
        }
    }

    onRoleMenuCancel() {
        this.resetCan()
        this.setState({
            visibleMenuModal: false,
            selectedRowKeys: []
        })
    }

    onRoleMenuOk() {
        const { menuList, selectedRowKeys, roleID } = this.state
        console.log(selectedRowKeys)
        const menus = menuList.filter(item => selectedRowKeys.indexOf(item.menuId) !== -1)
        this.setState({
            visibleMenuModal: false
        })
        const params = {
            roleID,
            menus
        }
        fetch.post('GasRole/AddRoleMenu', params).then(res => {
            if (res.isSuccess) {
                this.setState({
                    selectedRowKeys: []
                })
                this.getUser()
            }
        })
    }

    onUserEdit(e) {
        const { roleName, id } = e;
        this.setState({
            visible: true,
            modalTitle: '修改角色',
            roleName,
            id
        })
    }

    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys }, () => {
            console.log(this.state.selectedRowKeys)
        });
    }

    onAuthorityChange(checkboxItem, field) {
        const { menuList } = this.state
        const currentCheckbox = menuList.filter(item => checkboxItem.menuId === item.menuId)[0]
        currentCheckbox[field] = !currentCheckbox[field]
        this.setState({
            menuList
        })
    }

    render() {
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const { modalTitle } = this.state

        const CheckBoxItem = (item, field) => {
            return (
                <Checkbox checked={item[field]} onChange={this.onAuthorityChange.bind(this, item, field)} disabled={selectedRowKeys.indexOf(item.menuId) === -1}></Checkbox>
            )
        }

        const columns = [
            {
                title: '角色名',
                dataIndex: 'roleName',
                key: 'roleName',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
            },
            {
                title: '角色菜单',
                render: item => (
                    <div style={{ fontSize: '14px', cursor: 'pointer' }} onClick={this.openMenuModal.bind(this, item)} >
                        <Icon type="plus-square" style={{ marginRight: '5px' }}></Icon>
                        {
                            item.roleMenus.length ?
                                item.roleMenus.map((child, index) => {
                                    return (
                                        <span key={index}>{child.menuName}{index === item.roleMenus.length - 1 ? '' : '、'}</span>
                                    )
                                })
                                :
                                ''
                        }
                    </div>)
            }, {
                title: '操作',
                width: 100,
                render: item => (
                    <Row type="flex" justify="space-between">
                        <Col><Button style={{ width: '30px' }} onClick={this.onUserEdit.bind(this, item)} type="primary" size="small" icon="form"></Button></Col>
                        <Col> <Popconfirm
                            onConfirm={this.onDelUser.bind(this, item)}
                            title="确定删除吗？"
                            okText="删除"
                            cancelText="取消"
                            icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                        >
                            <Button style={{ width: '30px' }} type="danger" size="small" icon="delete"></Button>
                        </Popconfirm></Col>
                    </Row>
                )
            }
        ];

        const menusColumns = [
            {
                title: '菜单',
                key: 'menuName',
                dataIndex: 'menuName',
            },
            {
                title: '增加',
                render: item => (CheckBoxItem(item, 'canAdd'))
            },
            {
                title: '修改',
                render: item => (CheckBoxItem(item, 'canUpdate'))
            },
            {
                title: '删除',
                render: item => (CheckBoxItem(item, 'canDelete'))
            },
            {
                title: '导出',
                render: item => (CheckBoxItem(item, 'canExport'))
            }
        ]


        return (
            <div>
                <h3>角色管理</h3>
                <Button type="primary" onClick={this.openModal.bind(this)}>新增角色</Button>
                <div style={{ padding: '10px 0px' }}>
                    <Table dataSource={this.state.roleList} bordered columns={columns} rowKey="id" pagination={false} />
                </div>
                <Modal
                    title={modalTitle}
                    visible={this.state.visible}
                    onOk={this.handleOk.bind(this)}
                    cancelText='取消'
                    okText='确定'
                    onCancel={this.handleCancel.bind(this)}
                >
                    <Input value={this.state.roleName} placeholder='用户名' onChange={this.onRoleNameInput.bind(this)} />
                </Modal>
                <Modal
                    cancelText='取消'
                    okText='确定'
                    title={modalTitle}
                    onOk={this.onRoleMenuOk.bind(this)}
                    onCancel={this.onRoleMenuCancel.bind(this)}
                    visible={this.state.visibleMenuModal}>
                    <Table rowSelection={rowSelection} dataSource={this.state.menuList} columns={menusColumns} rowKey="menuId" pagination={false} />
                </Modal>
            </div>
        );
    }
}

export default RolePage;